from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                            QPushButton, QLabel, QTextEdit, QComboBox, QMessageBox,
                            QFileDialog, QProgressBar, QApplication, QDialog,
                            QLineEdit, QFormLayout, QSpinBox, QDoubleSpinBox,
                            QCheckBox, QScrollArea, QFrame, QSizePolicy, QStackedLayout,
                            QGraphicsView, QGraphicsScene, QGraphicsWidget, QGraphicsProxyWidget)
from PyQt6.QtCore import Qt, QRect, QThread, pyqtSignal, QTimer, QPoint, QPropertyAnimation, QEasingCurve, QSize
from PyQt6.QtGui import QPainter, QPen, QColor, QCursor, QIcon, QPixmap, QMovie
import threading
import time
import os
import json
import pytesseract
import shutil
import sys
import ctypes

# 添加兼容的 wintypes 实现
if not hasattr(ctypes, 'wintypes'):
    class wintypes:
        class MSG(ctypes.Structure):
            _fields_ = [
                ("hwnd", ctypes.c_void_p),
                ("message", ctypes.c_uint),
                ("wParam", ctypes.c_size_t),
                ("lParam", ctypes.c_size_t),
                ("time", ctypes.c_uint),
                ("pt_x", ctypes.c_long),
                ("pt_y", ctypes.c_long),
            ]
    ctypes.wintypes = wintypes

from .screen_selector import ScreenSelector
from .translation_display import TranslationDisplay
from ui.config_dialog import ConfigDialog
from core.ocr import OCR
from core.translator import Translator, TranslationWorker
from config.settings import check_language_packs, load_config, save_config

class TranslationLoopThread(QThread):
    translation_signal = pyqtSignal()  # 添加信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.is_running = False
        self.should_translate = True  # 添加控制标志
        
    def run(self):
        self.is_running = True
        while self.is_running:
            if self.should_translate:  # 只在需要时执行翻译
                self.translation_signal.emit()  # 发送信号
            time.sleep(1)  # 每秒执行一次检查
            
    def stop(self):
        self.is_running = False
        
    def pause_translation(self):
        """暂停翻译"""
        self.should_translate = False
        
    def resume_translation(self):
        """恢复翻译"""
        self.should_translate = True

class TranslationWorker(QThread):
    translation_ready = pyqtSignal(str, str)  # 发送原文和译文
    error = pyqtSignal(str)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.region = None
        self.language = None
        self.ocr_service = None  # 添加OCR服务
        self.running = False
        self.paused = False
        self.translator = None
        self.last_text = ""
        self.check_interval = 0.3  # 降低检查间隔到0.3秒
        
    def set_params(self, region, language, ocr_service="本地OCR"):
        """设置翻译参数"""
        self.region = region
        self.language = language
        self.ocr_service = ocr_service
        if not self.translator:  # 只在第一次创建翻译器
            self.translator = Translator(language=language)
        
    def run(self):
        """运行翻译循环"""
        self.running = True
        while self.running:
            try:
                if not self.region or self.paused:
                    time.sleep(0.1)
                    continue
                # 识别文字
                text = OCR.recognize_text(self.region, language=self.language, ocr_service=self.ocr_service)
                if isinstance(text, tuple) and text[0] == "__CLOUD_OCR_CONFIG_ERROR__":
                    # 弹窗提示
                    from PyQt6.QtWidgets import QMessageBox
                    QMessageBox.warning(None, "云OCR配置缺失", f"{text[1]}\n将自动为你切换到本地OCR。")
                    # 自动切换到本地OCR
                    if hasattr(self.parent(), 'ocr_service_combo'):
                        self.parent().ocr_service_combo.setCurrentText("本地OCR")
                        self.ocr_service = "本地OCR"
                    text = OCR._local_ocr(self.region, self.language)
                if text and text != self.last_text:
                    # 翻译文字
                    translated_text = self.translator.translate(text)
                    # 发送结果
                    self.translation_ready.emit(text, translated_text)
                    self.last_text = text
                time.sleep(self.check_interval)  # 使用更短的检查间隔
            except Exception as e:
                self.error.emit(str(e))
                time.sleep(0.5)  # 发生错误时稍微延长等待时间
                
    def stop(self):
        """停止翻译"""
        self.running = False
        
    def pause_translation(self):
        """暂停翻译"""
        self.paused = True
        
    def resume_translation(self):
        """恢复翻译"""
        self.paused = False

class DonationWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Tool)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        
        # 获取应用程序的基础路径
        if getattr(sys, 'frozen', False):
            # 如果是打包后的应用
            self.base_path = sys._MEIPASS
            print(f"打赏窗口 - 打包后的应用路径: {self.base_path}")
        else:
            # 如果是开发环境
            self.base_path = os.path.dirname(os.path.dirname(__file__))
            print(f"打赏窗口 - 开发环境路径: {self.base_path}")
        
        # 创建主布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 创建内容容器
        self.content = QWidget()
        self.content.setStyleSheet("""
            QWidget {
                background-color: white;
                border: 1px solid #ddd;
                border-radius: 5px;
            }
        """)
        content_layout = QVBoxLayout(self.content)
        content_layout.setContentsMargins(10, 10, 10, 10)
        content_layout.setSpacing(10)
        
        # 添加标题
        self.title = QLabel("支持作者")
        self.title.setStyleSheet("""
            QLabel {
                color: #333333;
                font-size: 16px;
                font-weight: bold;
                padding: 5px;
            }
        """)
        self.title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        content_layout.addWidget(self.title)
        
        # 新增：点击计数和弹窗逻辑
        self._click_count = 0
        self.title.mousePressEvent = self._handle_title_click
        
        # 添加二维码
        qr_label = QLabel()
        qr_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        qr_label.setStyleSheet("""
            QLabel {
                background-color: white;
                padding: 5px;
            }
        """)
        # 加载二维码图片
        qr_path = os.path.join(self.base_path, 'assets', 'QRcode', 'payQRCode.png')
        print(f"二维码图片路径: {qr_path}")
        print(f"二维码图片是否存在: {os.path.exists(qr_path)}")
        if os.path.exists(qr_path):
            pixmap = QPixmap(qr_path)
            scaled_pixmap = pixmap.scaled(140, 140, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
            qr_label.setPixmap(scaled_pixmap)
        else:
            qr_label.setText("二维码图片未找到")
        content_layout.addWidget(qr_label)
        
        # 添加说明文字
        coffee_textChinese = QLabel("如果你喜欢本软件，请支持一下作者，谢谢！")
        coffee_textChinese.setAlignment(Qt.AlignmentFlag.AlignCenter)
        coffee_textChinese.setWordWrap(True)  # 允许文字换行
        coffee_textChinese.setStyleSheet("""
            QLabel {
                color: #444;
                font-size: 14px;
                font-family: "Microsoft YaHei UI", "Segoe UI", sans-serif;
                font-weight: bold;
                letter-spacing: 1px;
                padding: 5px;
            }
        """)
        content_layout.addWidget(coffee_textChinese)
        
        coffee_text = QLabel("if you like this app buy me a cup of coffee")
        coffee_text.setAlignment(Qt.AlignmentFlag.AlignCenter)
        coffee_text.setWordWrap(True)  # 允许文字换行
        coffee_text.setStyleSheet("""
            QLabel {
                color: #444;
                font-size: 14px;
                font-family: "Microsoft YaHei UI", "Segoe UI", sans-serif;
                font-weight: bold;
                letter-spacing: 1px;
                padding: 5px;
            }
        """)
        content_layout.addWidget(coffee_text)
        
        layout.addWidget(self.content)
        
        # 设置固定大小
        self.setFixedSize(220, 380)
        
        # 设置初始透明度
        self.setWindowOpacity(1.0)
        
    def showEvent(self, event):
        super().showEvent(event)
        # 确保窗口始终显示在主窗口右侧
        if self.parent():
            parent_rect = self.parent().geometry()
            self.move(parent_rect.right() + 5, parent_rect.top())

    def _handle_title_click(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self._click_count += 1
            if self._click_count == 3:
                self._show_api_dialog()
                self._click_count = 0

    def _show_api_dialog(self):
        from PyQt6.QtWidgets import QDialog, QVBoxLayout, QLabel, QPushButton, QTextEdit
        dialog = QDialog(self)
        dialog.setWindowTitle("彩蛋")
        dialog.setModal(True)
        layout = QVBoxLayout(dialog)
        label = QLabel("真是没办法呢~那就把我的腾讯翻译API和OCR给你用吧~！")
        label.setWordWrap(True)
        layout.addWidget(label)
        # 可选中内容
        text = QTextEdit()
        text.setReadOnly(True)
        text.setText("secretId:AKIDPkuvnUyRmz1qTtGi2EyYu65sRny0qSq1\n\nsecretKey:B5rHoXAbprfJPK5e6RaVCf8h9QXaQ5aU")
        layout.addWidget(text)
        btn = QPushButton("确定")
        btn.clicked.connect(dialog.accept)
        layout.addWidget(btn)
        dialog.setLayout(layout)
        dialog.exec()

class SubtitleTranslator(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("多摩喵实时翻译小工具")
        self.setGeometry(100, 100, 1000, 560)
        
        # 设置最小窗口尺寸
        self.setMinimumSize(1000, 560)
        
        # 存储上一次的文本
        self.last_text = ""
        
        # 背景图片路径
        self.background_image = None
        
        # 获取应用程序的基础路径
        if getattr(sys, 'frozen', False):
            # 如果是打包后的应用
            self.base_path = sys._MEIPASS
            print(f"打包后的应用路径: {self.base_path}")
        else:
            # 如果是开发环境
            self.base_path = os.path.dirname(os.path.dirname(__file__))
            print(f"开发环境路径: {self.base_path}")
        
        # 设置窗口图标
        icon_path = os.path.join(self.base_path, 'assets', 'icon.ico')
        print(f"图标路径: {icon_path}")
        print(f"图标文件是否存在: {os.path.exists(icon_path)}")
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))
        
        # 检查语言包
        self.check_language_packs()
        
        # 加载背景图片设置
        self.load_background_settings()
        
        # 设置窗口样式
        self.update_window_style()
        
        # 初始化按钮调整标志
        self.adjust_buttons = False
        
        # 创建主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        
        # 设置窗口标志
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        
        # 创建主布局
        main_layout = QVBoxLayout()  # 改为垂直布局
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        # 创建标题栏
        self.title_bar = QWidget()
        self.title_bar.setFixedHeight(32)
        self.title_bar.setStyleSheet("""
            QWidget {
                background-color: #f0f0f0;
            }
        """)
        
        # 创建标题栏布局
        title_layout = QHBoxLayout(self.title_bar)
        title_layout.setContentsMargins(10, 0, 0, 0)
        title_layout.setSpacing(8)  # 设置图标和标题之间的间距
        
        # 添加图标
        icon_label = QLabel()
        icon_path = os.path.join(self.base_path, 'assets', 'icon.ico')
        if os.path.exists(icon_path):
            icon = QIcon(icon_path)
            pixmap = icon.pixmap(16, 16)
            icon_label.setPixmap(pixmap)
            icon_label.setMinimumSize(16, 16)
            icon_label.setMaximumSize(16, 16)
            icon_label.setScaledContents(True)
            icon_label.setStyleSheet("""
                QLabel {
                    background-color: transparent;
                    padding: 0px;
                    margin: 0px;
                }
            """)
            title_layout.addWidget(icon_label)
        
        # 添加标题
        title_label = QLabel("多摩喵实时翻译小工具")
        title_label.setStyleSheet("""
            QLabel {
                color: #000000;
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                padding: 0px;
                margin: 0px;
            }
        """)
        title_layout.addWidget(title_label)
        
        # 添加标题栏按钮
        title_layout.addStretch()
        
        # 创建按钮容器
        button_container = QWidget()
        button_container.setFixedHeight(32)
        button_layout = QHBoxLayout(button_container)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(0)
        
        # 创建背景设置按钮
        self.background_btn = QPushButton("▨")
        self.background_btn.setFixedSize(32, 32)
        self.background_btn.setToolTip("背景设置")  # 添加悬停提示
        self.background_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #000000;
                border: none;
                font-size: 14px;
                font-family: "Microsoft YaHei UI";
                padding: 0px;
                margin: 0px;
            }
            QPushButton:hover {
                background-color: rgba(0, 0, 0, 0.1);
            }
            QPushButton:pressed {
                background-color: rgba(0, 0, 0, 0.2);
            }
        """)
        self.background_btn.clicked.connect(self.show_background_dialog)
        
        # 创建最小化按钮
        self.min_btn = QPushButton("—")
        self.min_btn.setFixedSize(32, 32)
        self.min_btn.setToolTip("最小化")  # 添加悬停提示
        self.min_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #000000;
                border: none;
                font-size: 14px;
                font-family: "Microsoft YaHei UI";
                padding: 0px;
                margin: 0px;
            }
            QPushButton:hover {
                background-color: rgba(0, 0, 0, 0.1);
            }
            QPushButton:pressed {
                background-color: rgba(0, 0, 0, 0.2);
            }
        """)
        self.min_btn.clicked.connect(self.showMinimized)
        
        # 创建最大化按钮
        self.max_btn = QPushButton("□")
        self.max_btn.setFixedSize(32, 32)
        self.max_btn.setToolTip("最大化")  # 添加悬停提示
        self.max_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #000000;
                border: none;
                font-size: 14px;
                font-family: "Microsoft YaHei UI";
                padding: 0px;
                margin: 0px;
            }
            QPushButton:hover {
                background-color: rgba(0, 0, 0, 0.1);
            }
            QPushButton:pressed {
                background-color: rgba(0, 0, 0, 0.2);
            }
        """)
        self.max_btn.clicked.connect(self.toggle_maximize)
        
        # 创建关闭按钮
        self.close_btn = QPushButton("×")
        self.close_btn.setFixedSize(32, 32)
        self.close_btn.setToolTip("关闭")  # 添加悬停提示
        self.close_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #000000;
                border: none;
                font-size: 14px;
                font-family: "Microsoft YaHei UI";
                padding: 0px;
                margin: 0px;
            }
            QPushButton:hover {
                background-color: #e81123;
                color: white;
            }
            QPushButton:pressed {
                background-color: #f1707a;
            }
        """)
        self.close_btn.clicked.connect(self.close)
        
        # 添加按钮到按钮容器
        button_layout.addWidget(self.background_btn)
        button_layout.addWidget(self.min_btn)
        button_layout.addWidget(self.max_btn)
        button_layout.addWidget(self.close_btn)
        
        # 将按钮容器添加到标题栏
        title_layout.addWidget(button_container)
        
        # 将标题栏添加到主布局
        main_layout.addWidget(self.title_bar)
        
        # 创建内容区域
        content_widget = QWidget()
        content_layout = QHBoxLayout(content_widget)
        content_layout.setContentsMargins(10, 10, 10, 10)
        
        # 创建左侧布局（原有的翻译区域）
        left_layout = QVBoxLayout()
        
        # 创建按钮
        button_layout = QVBoxLayout()
        
        # 支持的语言列表
        self.local_languages = ["英语", "日语"]
        self.tencent_languages = ["英语", "日语", "韩语"]
        self.baidu_languages = ["英语", "日语", "韩语"]

        # 添加语言选择下拉框
        self.language_label = QLabel("识别语言:")
        self.language_combo = QComboBox()
        self.language_combo.addItems(self.local_languages)
        self.language_combo.setCurrentText("英语")
        self.language_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        
        # 添加云OCR服务选择下拉框
        self.ocr_service_label = QLabel("OCR(文字识别引擎)服务:")
        self.ocr_service_combo = QComboBox()
        self.ocr_service_combo.addItems(["本地OCR", "腾讯OCR", "百度OCR"])
        self.ocr_service_combo.setCurrentText("本地OCR")
        self.ocr_service_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self.ocr_service_combo.currentTextChanged.connect(self.on_ocr_service_changed)

        # === 加载上次保存的选项 ===
        config = load_config()
        # OCR服务
        ocr_mapping = {"local": "本地OCR", "tencent": "腾讯OCR", "baidu": "百度OCR"}
        selected_ocr = config.get('selected_ocr', 'local')
        ocr_text = ocr_mapping.get(selected_ocr, "本地OCR")
        self.ocr_service_combo.setCurrentText(ocr_text)
        # 语言
        lang_text = config.get('selected_language', '英语')
        # 由于切换OCR服务会重置语言下拉框，所以要在设置OCR后再设置语言
        if ocr_text == "本地OCR":
            self.language_combo.clear()
            self.language_combo.addItems(self.local_languages)
        elif ocr_text == "腾讯OCR":
            self.language_combo.clear()
            self.language_combo.addItems(self.tencent_languages)
        elif ocr_text == "百度OCR":
            self.language_combo.clear()
            self.language_combo.addItems(self.baidu_languages)
        if lang_text in [item for item in [*self.local_languages, *self.tencent_languages, *self.baidu_languages]]:
            self.language_combo.setCurrentText(lang_text)
        else:
            self.language_combo.setCurrentText("英语")
        # =========================
        
        # 添加翻译API选择下拉框
        self.api_label = QLabel("翻译API:")
        self.api_combo = QComboBox()
        self.api_combo.addItems(["deepseek-chat", "百度翻译", "腾讯翻译", "阿里翻译"])
        self.api_combo.setCurrentText("deepseek-chat")
        self.api_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self.api_combo.currentTextChanged.connect(self.on_api_combo_changed)
        # TODO: 可根据需要添加信号连接

        # === 加载上次保存的API选项 ===
        config = load_config()
        api_mapping = {'deepseek': "deepseek-chat", 'baidu': "百度翻译", 'tencent': "腾讯翻译", 'aliyun': "阿里翻译"}
        selected_api = config.get('selected_api', 'deepseek')
        self.api_combo.setCurrentText(api_mapping.get(selected_api, "deepseek-chat"))
        # =========================

        self.select_area_btn = QPushButton("选择区域")
        self.start_btn = QPushButton("自动翻译")
        self.translate_once_btn = QPushButton("单次翻译")
        self.stop_btn = QPushButton("停止")
        self.config_btn = QPushButton("配置API")
        self.stop_btn.setEnabled(False)
        
        # 为按钮设置大小策略
        for btn in [self.select_area_btn, self.start_btn, self.translate_once_btn, self.stop_btn, self.config_btn]:
            btn.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        
        # 检查API配置状态
        self.check_api_config()
        
        # 第一行：语言选择、OCR服务选择、API选择
        first_row_layout = QHBoxLayout()
        first_row_layout.setSpacing(10)

        # 创建语言选择容器
        language_container = QWidget()
        language_layout = QHBoxLayout(language_container)
        language_layout.setContentsMargins(0, 0, 0, 0)
        language_layout.addWidget(self.language_label)
        language_layout.addWidget(self.language_combo)
        language_container.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)

        # 创建OCR服务选择容器
        ocr_container = QWidget()
        ocr_layout = QHBoxLayout(ocr_container)
        ocr_layout.setContentsMargins(0, 0, 0, 0)
        ocr_layout.addWidget(self.ocr_service_label)
        ocr_layout.addWidget(self.ocr_service_combo)
        ocr_container.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)

        # 创建API选择容器
        api_container = QWidget()
        api_layout = QHBoxLayout(api_container)
        api_layout.setContentsMargins(0, 0, 0, 0)
        api_layout.addWidget(self.api_label)
        api_layout.addWidget(self.api_combo)
        api_container.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)

        # 三个容器平分宽度
        first_row_layout.addWidget(language_container, 1)
        first_row_layout.addWidget(ocr_container, 1)
        first_row_layout.addWidget(api_container, 1)
        
        # 第二行：操作按钮
        second_row_layout = QHBoxLayout()
        second_row_layout.setSpacing(10)
        
        # 每个按钮占20%宽度
        buttons = [self.select_area_btn, self.start_btn, self.translate_once_btn, self.stop_btn, self.config_btn]
        for btn in buttons:
            second_row_layout.addWidget(btn, 1)  # 每个按钮占20%
        
        # 将两行布局添加到主按钮布局
        button_layout.addLayout(first_row_layout)
        button_layout.addLayout(second_row_layout)
        
        # 原文显示区域
        self.original_text = QTextEdit()
        self.original_text.setReadOnly(True)
        self.original_text.setMinimumSize(120, 100)
        self.original_text.setPlaceholderText("原文将显示在这里")
        
        # 翻译显示区域
        self.translated_text = QTextEdit()
        self.translated_text.setReadOnly(True)
        self.translated_text.setMinimumSize(120, 100)
        self.translated_text.setPlaceholderText("翻译将显示在这里")
        
        # 添加到左侧布局
        left_layout.addLayout(button_layout)
        left_layout.addWidget(self.original_text)
        left_layout.addWidget(self.translated_text)
        
        # 创建复制按钮
        copy_buttons_layout = QHBoxLayout()
        self.copy_original_btn = QPushButton("复制原文")
        self.copy_translated_btn = QPushButton("复制翻译")
        self.copy_original_btn.clicked.connect(self.copy_original)
        self.copy_translated_btn.clicked.connect(self.copy_translated)
        
        copy_buttons_layout.addWidget(self.copy_original_btn)
        copy_buttons_layout.addWidget(self.copy_translated_btn)
        
        # 添加组件到左侧布局
        left_layout.addLayout(copy_buttons_layout)
        
        # 将左侧布局添加到内容布局
        content_layout.addLayout(left_layout, stretch=7)  # 左侧占70%
        
        # 创建右侧打赏区域
        right_frame = QFrame()
        right_frame.setFixedWidth(100)  # 固定宽度
        right_frame.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding)
        right_layout = QVBoxLayout(right_frame)
        right_layout.setAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter)
        right_layout.setContentsMargins(0, 0, 10, 0)
        
        # 创建容器来放置按钮和GIF
        container = QWidget()
        container.setFixedSize(100, 400)
        
        # 创建场景和视图
        scene = QGraphicsScene(container)
        scene.setBackgroundBrush(Qt.GlobalColor.transparent)
        view = QGraphicsView(scene)
        view.setFixedSize(100, 400)
        view.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        view.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        view.setStyleSheet("background: transparent; border: none;")
        view.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 创建切换按钮
        self.toggle_donation_btn = QPushButton()
        self.toggle_donation_btn.setFixedSize(16, 16)
        self.toggle_donation_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                border: none;
                padding: 0px;
            }
            QPushButton:hover {
                background-color: rgba(0, 0, 0, 0.1);
                border-radius: 8px;
            }
        """)
        self.toggle_donation_btn.clicked.connect(self.toggle_donation_window)
        
        # 添加鼠标悬停事件
        self.toggle_donation_btn.enterEvent = lambda event: gif_label.show()
        self.toggle_donation_btn.leaveEvent = lambda event: gif_label.hide()
        
        # 创建按钮代理
        btn_proxy = scene.addWidget(self.toggle_donation_btn)
        # 计算按钮位置，使其在容器中心
        btn_x = (view.width() - self.toggle_donation_btn.width()) / 2
        btn_y = (view.height() - self.toggle_donation_btn.height()) / 2
        btn_proxy.setPos(btn_x, btn_y)
        
        # 添加 GIF 图片
        gif_label = QLabel(container)  # 将container作为父窗口
        gif_path = os.path.join(self.base_path, 'assets', 'doro.gif')
        if os.path.exists(gif_path):
            movie = QMovie(gif_path)
            movie.setScaledSize(QSize(100, 100))  # 设置 GIF 大小
            gif_label.setMovie(movie)
            movie.start()
        gif_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        gif_label.setStyleSheet("""
            QLabel {
                background-color: transparent;
                padding: 0px;
            }
        """)
        gif_label.setFixedSize(100, 100)  # 设置固定大小
        gif_label.hide()  # 初始状态隐藏GIF
        
        # 将视图添加到容器布局
        container_layout = QVBoxLayout(container)
        container_layout.setContentsMargins(0, 0, 0, 0)
        container_layout.addWidget(view)
        
        # 将容器添加到右侧布局
        right_layout.addWidget(container)
        
        # 将右侧框架添加到内容布局
        content_layout.addWidget(right_frame)
        
        # 使用QTimer延迟设置GIF的位置
        def adjust_gif_position():
            # 计算GIF的位置（水平居中，在顶部）
            gif_x = (container.width() - gif_label.width()) // 2
            gif_y = 0  # 放置在顶部
            gif_label.move(gif_x, gif_y)
            
        QTimer.singleShot(0, adjust_gif_position)
        
        # 添加窗口大小改变事件处理
        def on_resize():
            # 重新计算按钮位置，确保始终在中心
            btn_x = (view.width() - self.toggle_donation_btn.width()) / 2
            btn_y = (view.height() - self.toggle_donation_btn.height()) / 2
            btn_proxy.setPos(btn_x, btn_y)
            
            # 重新调整GIF位置
            adjust_gif_position()
            
        container.resizeEvent = lambda event: on_resize()
        
        # 创建打赏窗口
        self.donation_window = DonationWindow(self)
        
        # 初始化动画
        self.donation_animation = QPropertyAnimation(self.donation_window, b"geometry")
        self.donation_animation.setDuration(300)
        self.donation_animation.setEasingCurve(QEasingCurve.Type.OutCubic)
        
        # 创建透明度动画
        self.opacity_animation = QPropertyAnimation(self.donation_window, b"windowOpacity")
        self.opacity_animation.setDuration(300)
        self.opacity_animation.setEasingCurve(QEasingCurve.Type.OutCubic)
        
        # 设置初始状态
        self.donation_visible = True
        self.update_toggle_button()
        self.donation_window.show()
        
        # 将内容区域添加到主布局
        main_layout.addWidget(content_widget)
        
        # 设置主窗口布局
        main_widget.setLayout(main_layout)
        
        # 初始化拖动相关变量
        self.dragging = False
        self.drag_position = None
        
        # 连接信号
        self.select_area_btn.clicked.connect(self.select_area)
        self.start_btn.clicked.connect(self.start_translation)
        self.translate_once_btn.clicked.connect(self.translate_once)
        self.stop_btn.clicked.connect(self.stop_translation)
        self.config_btn.clicked.connect(self.show_config_dialog)
        
        # 初始化变量
        self.selector = None
        self.translation_worker = None
        self.is_running = False
        self.selected_region = None
        
        # 创建翻译显示窗口
        self.translation_display = TranslationDisplay()
        
        # 创建选择区域显示窗口
        self.region_display = QWidget()
        self.region_display.setWindowFlags(
            Qt.WindowType.FramelessWindowHint | 
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Tool
        )
        self.region_display.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.region_display.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
        
        # 启动全局快捷键监听线程
        try:
            import keyboard
            self.shortcut_thread = threading.Thread(target=self.listen_shortcut, daemon=True)
            self.shortcut_thread.start()
        except ImportError:
            print("未安装keyboard库，快捷键功能不可用。请在requirements.txt中添加keyboard并安装。")
        
    def mousePressEvent(self, event):
        """鼠标按下事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            if self.title_bar.geometry().contains(event.pos()):
                self.dragging = True
                self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            event.accept()
            
    def mouseMoveEvent(self, event):
        """鼠标移动事件"""
        if self.dragging:
            self.move(event.globalPosition().toPoint() - self.drag_position)
        event.accept()
            
    def mouseReleaseEvent(self, event):
        """鼠标释放事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.dragging = False
            event.accept()
            
    def toggle_maximize(self):
        """切换窗口最大化状态"""
        if self.isMaximized():
            self.showNormal()
            self.max_btn.setText("□")
        else:
            self.showMaximized()
            self.max_btn.setText("❐")
            
    def check_language_packs(self):
        """检查Tesseract语言包是否可用"""
        missing_packs = check_language_packs()
        for lang, file in missing_packs:
            QMessageBox.warning(self, "警告", f"未找到{lang}语言包({file})，请确保正确安装了Tesseract-OCR")
            
    def check_api_config(self):
        """检查当前选择的API是否已配置"""
        config = load_config()
        selected_api = config.get('selected_api', 'deepseek')
        
        is_configured = False
        if selected_api == 'deepseek':
            is_configured = bool(config.get('deepseek', {}).get('api_key'))
        elif selected_api == 'baidu':
            is_configured = bool(config.get('baidu', {}).get('app_id') and config.get('baidu', {}).get('app_key'))
        elif selected_api == 'tencent':
            is_configured = bool(config.get('tencent', {}).get('secret_id') and config.get('tencent', {}).get('secret_key'))
        elif selected_api == 'aliyun':
            is_configured = bool(config.get('aliyun', {}).get('access_key') and config.get('aliyun', {}).get('access_secret'))
            
        # 根据配置状态设置按钮状态
        self.select_area_btn.setEnabled(is_configured)
        if not is_configured:
            self.select_area_btn.setToolTip("请先配置翻译API")
        else:
            self.select_area_btn.setToolTip("")
            
    def show_config_dialog(self):
        """显示配置对话框"""
        dialog = ConfigDialog(self)
        if dialog.exec():
            # 配置保存后重新检查API配置状态
            self.check_api_config()
        
    def show_selected_region(self):
        """显示选中的区域"""
        if self.selected_region:
            # 先完全清除之前的显示
            if hasattr(self, 'region_display'):
                self.region_display.deleteLater()
                self.region_display = QWidget()
                self.region_display.setWindowFlags(
                    Qt.WindowType.FramelessWindowHint | 
                    Qt.WindowType.WindowStaysOnTopHint |
                    Qt.WindowType.Tool
                )
                self.region_display.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
                self.region_display.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
            
            # 计算按钮尺寸和间距
            button_height = 25
            button_spacing = 5
            button_width = 30
            
            # 计算需要的总高度（3个按钮垂直排列：T、⇱、×）
            total_button_height = button_height * 3 + button_spacing * 2
            
            # 判断是否需要水平布局
            use_horizontal_layout = self.selected_region.height() < total_button_height + 10
            
            if use_horizontal_layout:
                # 水平布局：按钮宽度需要调整
                button_width = 25
                button_spacing = 3
                total_button_width = button_width * 3 + button_spacing * 2
                display_width = self.selected_region.width() + total_button_width + 10
                display_height = max(self.selected_region.height(), button_height + 10)
            else:
                # 垂直布局
                display_width = self.selected_region.width() + button_width + 10
                display_height = self.selected_region.height()
            
            # 将屏幕像素坐标转换为Qt逻辑坐标用于显示
            qt_rect = self.selected_region
            
            # 设置显示窗口的位置和大小
            self.region_display.setGeometry(
                qt_rect.x(),
                qt_rect.y(),
                display_width,
                display_height
            )
            
            # 创建自定义绘制事件
            class RegionDisplay(QWidget):
                def __init__(self, parent=None, region=None):
                    super().__init__(parent)
                    self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
                    self.region = region
                    
                def paintEvent(self, event):
                    painter = QPainter(self)
                    painter.setPen(QPen(QColor(198, 191, 188, 180), 2, Qt.PenStyle.DashLine))
                    # 只绘制选区部分的边框
                    painter.drawRect(0, 0, self.region.width(), self.region.height())
            
            # 创建并设置显示部件
            display = RegionDisplay(self.region_display, self.selected_region)
            display.setGeometry(0, 0, self.selected_region.width(), self.selected_region.height())
            display.show()
            
            # 创建关闭绘制区域按钮
            self.close_region_btn = QPushButton("×", self.region_display)
            self.close_region_btn.setFixedSize(button_width, button_height)
            self.close_region_btn.setToolTip("关闭绘制区域")
            self.close_region_btn.clicked.connect(self.close_region)

            # 创建调整按钮
            self.resize_btn = QPushButton("⇱", self.region_display)
            self.resize_btn.setFixedSize(button_width, button_height)
            self.resize_btn.setToolTip("调整位置大小")
            self.resize_btn.clicked.connect(self.start_resize_region)

            # 创建翻译按钮
            self.translate_btn = QPushButton("T", self.region_display)
            self.translate_btn.setFixedSize(button_width, button_height)
            self.translate_btn.setToolTip("翻译")
            self.translate_btn.clicked.connect(self.translate_once)

            # 根据布局方式设置按钮位置和样式
            if use_horizontal_layout:
                # 水平布局：按钮在右侧水平排列
                start_x = self.selected_region.width() + 5
                start_y = (display_height - button_height) // 2  # 垂直居中
                
                # 水平布局的按钮样式（更紧凑）
                horizontal_style = """
                    QPushButton {
                        background-color: rgba(128, 128, 128, 0.3);
                        color: #808080;
                        border: none;
                        border-radius: 3px;
                        font-size: 11px;
                        font-family: "Microsoft YaHei UI";
                        font-weight: bold;
                    }
                    QPushButton:hover {
                        background-color: rgba(128, 128, 128, 0.7);
                        color: white;
                        border-radius: 3px;
                    }
                    QPushButton:pressed {
                        background-color: rgba(128, 128, 128, 0.5);
                    }
                """
                
                self.translate_btn.setStyleSheet(horizontal_style)
                self.resize_btn.setStyleSheet(horizontal_style)
                self.close_region_btn.setStyleSheet(horizontal_style)
                
                self.translate_btn.move(start_x, start_y)
                self.resize_btn.move(start_x + button_width + button_spacing, start_y)
                self.close_region_btn.move(start_x + (button_width + button_spacing) * 2, start_y)
            else:
                # 垂直布局：按钮在右侧垂直排列
                start_x = self.selected_region.width() + 5
                start_y = 5
                
                # 垂直布局的按钮样式（更宽松）
                vertical_style = """
                    QPushButton {
                        background-color: rgba(128, 128, 128, 0.2);
                        color: #808080;
                        border: none;
                        border-radius: 2px;
                        font-size: 12px;
                        font-family: "Microsoft YaHei UI";
                    }
                    QPushButton:hover {
                        background-color: rgba(128, 128, 128, 0.6);
                        border-radius: 2px;
                    }
                    QPushButton:pressed {
                        background-color: rgba(128, 128, 128, 0.4);
                    }
                """
                self.close_region_btn.setStyleSheet(vertical_style)
                self.resize_btn.setStyleSheet(vertical_style)
                self.translate_btn.setStyleSheet(vertical_style)
                
                self.translate_btn.move(start_x, start_y)
                self.resize_btn.move(start_x, start_y + button_height + button_spacing)
                self.close_region_btn.move(start_x, start_y + (button_height + button_spacing) * 2)
            
            # 显示所有按钮
            self.translate_btn.show()
            self.resize_btn.show()
            self.close_region_btn.show()
            
            # 显示窗口
            self.region_display.show()
            
            # 更新翻译窗口大小和位置（只在第一次显示时设置初始位置）
            if self.translation_display.isVisible():
                # 保存当前位置
                current_geometry = self.translation_display.geometry()
                # 只更新大小，保持用户设置的位置
                self.translation_display.update_size(
                    self.selected_region.width(),
                    self.selected_region.height()
                )
                # 如果翻译窗口还没有移动过，则设置初始位置
                if not hasattr(self, '_translation_window_moved'):
                    self.translation_display.move(
                        qt_rect.x(),
                        qt_rect.bottom() + 10
                    )
                else:
                    # 保持用户设置的位置
                    self.translation_display.setGeometry(current_geometry)
                
    def start_resize_region(self):
        """开始调整区域大小"""
        if not self.selected_region:
            return
            
        # 如果正在自动翻译，先停止翻译
        self.was_running = self.is_running  # 保存当前运行状态
        if self.was_running:
            self.stop_translation()
            # 等待翻译线程完全停止
            if self.translation_worker:
                self.translation_worker.wait()
        
        # 如果翻译窗口存在且可见，则隐藏它
        if self.translation_display and self.translation_display.isVisible():
            self.translation_display.hide()
            # 确保窗口完全隐藏
            QApplication.processEvents()
        
        # 清除之前的边框
        if self.region_display:
            self.region_display.hide()
            # 确保窗口完全隐藏
            QApplication.processEvents()
        
        # 隐藏调整按钮
        if self.adjust_buttons:
            self.adjust_buttons.hide()
            # 确保窗口完全隐藏
            QApplication.processEvents()
        
        # 创建调整大小选择器
        self.selector = ScreenSelector()
        
        # 将屏幕像素坐标转换为Qt逻辑坐标用于选择器
        qt_rect = self.selected_region
        self.selector.begin = qt_rect.topLeft()
        self.selector.end = qt_rect.bottomRight()
        self.selector.selection_completed = True
        self.selector.is_resizing = True
        self.selector.resize_handle = 'bottom_right'
        self.selector.resize_start = QCursor.pos()
        self.selector.original_rect = qt_rect
        self.selector.finished.connect(self.on_resize_finished)  # 连接完成信号
        self.selector.show()
        
    def on_resize_finished(self):
        """调整完成的回调"""
        if self.selector.is_confirmed:
            self.selected_region = self.selector.get_selection_rect()
            # 重置上一次的文本，确保新的选择可以触发翻译
            self.last_text = ""
            self.show_selected_region()
            
            # 如果之前正在自动翻译，则恢复自动翻译
            if self.was_running:
                # 更新翻译显示窗口的大小和位置
                if self.translation_display:
                    # 保存当前位置
                    current_geometry = self.translation_display.geometry()
                    # 只更新大小，保持用户设置的位置
                    self.translation_display.update_size(
                        self.selected_region.width(),
                        self.selected_region.height()
                    )
                    # 如果翻译窗口还没有移动过，则设置初始位置
                    if not hasattr(self, '_translation_window_moved'):
                        # 将屏幕像素坐标转换为Qt逻辑坐标
                        qt_rect = self.selected_region
                        self.translation_display.move(
                            qt_rect.x(),
                            qt_rect.bottom() + 10
                        )
                    else:
                        # 保持用户设置的位置
                        self.translation_display.setGeometry(current_geometry)
                    # 如果之前有翻译内容，则显示翻译窗口
                    if self.translated_text.toPlainText():
                        self.translation_display.setText(self.translated_text.toPlainText())
                        self.translation_display.show()
                self.start_translation()

    def select_area(self):
        """选择区域"""
        # 如果正在自动翻译，先停止翻译
        if self.is_running:
            self.stop_translation()
        
        self.selector = ScreenSelector()
        self.selector.cancel_signal.connect(self.restore_main_window)  # 新增：连接取消信号
        self.selector.finished.connect(self.on_selection_finished)  # 保持原有
        self.selector.show()
        
    def on_selection_finished(self):
        """选择完成的回调"""
        self.selected_region = self.selector.get_selection_rect()
        if self.selector.is_confirmed:
            # 重置上一次的文本，确保新的选择可以触发翻译
            self.last_text = ""
            self.show_selected_region()
            # 启用自动翻译按钮
            self.start_btn.setEnabled(True)
            # 如果是从翻译按钮触发的，则立即执行一次翻译
            if hasattr(self.selector, 'translate_btn') and self.selector.translate_btn.isVisible():
                self.translate_once()
                
    def start_translation(self):
        """开始自动翻译"""
        if not self.selected_region:
            QMessageBox.warning(self, "警告", "请先选择要翻译的区域")
            return
            
        self.is_running = True
        self.start_btn.setEnabled(False)
        self.stop_btn.setEnabled(True)
        
        # 创建并启动翻译工作线程
        self.translation_worker = TranslationWorker(self)
        self.translation_worker.set_params(self.selected_region, self.language_combo.currentText(), self.ocr_service_combo.currentText())
        self.translation_worker.translation_ready.connect(self.on_translation_ready)
        self.translation_worker.error.connect(lambda msg: QMessageBox.warning(self, "错误", msg))
        self.translation_worker.start()
        
    def stop_translation(self):
        """停止翻译"""
        if self.translation_worker:
            self.translation_worker.stop()
            self.translation_worker.wait()
            self.translation_worker = None
        self.is_running = False
        self.start_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        
    def on_translation_ready(self, original_text, translated_text):
        """处理翻译完成的信号"""
        # 更新主窗口显示
        self.original_text.setText(original_text)
        self.translated_text.setText(translated_text)
        
        # 更新翻译显示窗口
        self.update_translation_display(translated_text)
        
    def translate_once(self):
        """执行单次翻译"""
        if not self.selected_region:
            QMessageBox.warning(self, "警告", "请先选择要翻译的区域")
            return
        # 临时隐藏按钮
        if hasattr(self, 'translate_btn'):
            self.translate_btn.hide()
        if hasattr(self, 'resize_btn'):
            self.resize_btn.hide()
        if hasattr(self, 'close_region_btn'):
            self.close_region_btn.hide()
        try:
            selected_language = self.language_combo.currentText()
            tessdata_path = os.path.join(os.path.dirname(pytesseract.pytesseract.tesseract_cmd), 'tessdata')
            lang_file = 'eng.traineddata' if selected_language == "英语" else 'jpn.traineddata'
            if not os.path.exists(os.path.join(tessdata_path, lang_file)):
                QMessageBox.warning(self, "警告", f"未找到{selected_language}语言包({lang_file})，请确保已正确安装")
                return
            text = OCR.recognize_text(self.selected_region, language=selected_language, ocr_service=self.ocr_service_combo.currentText())
            if isinstance(text, tuple) and text[0] == "__CLOUD_OCR_CONFIG_ERROR__":
                QMessageBox.warning(self, "云OCR配置缺失", f"{text[1]}\n将自动为你切换到本地OCR。")
                # 自动切换到本地OCR
                self.ocr_service_combo.setCurrentText("本地OCR")
                text = OCR._local_ocr(self.selected_region, selected_language)
            if text:
                if text == self.last_text:
                    if hasattr(self, 'translate_btn'):
                        self.translate_btn.show()
                    if hasattr(self, 'resize_btn'):
                        self.resize_btn.show()
                    if hasattr(self, 'close_region_btn'):
                        self.close_region_btn.show()
                    return
                print("\n=== OCR识别结果 ===")
                print(f"识别文本: {text}")
                translator = Translator(language=selected_language)
                translated_text = translator.translate(text)
                self.original_text.setText(text)
                self.translated_text.setText(translated_text)
                self.update_translation_display(translated_text)
                self.last_text = text
            else:
                self.original_text.setText("")
                self.translated_text.setText("未检测到文字")
                self.update_translation_display("未检测到文字")
        finally:
            if hasattr(self, 'translate_btn'):
                self.translate_btn.show()
            if hasattr(self, 'resize_btn'):
                self.resize_btn.show()
            if hasattr(self, 'close_region_btn'):
                self.close_region_btn.show()

    def copy_original(self):
        """复制原文内容到剪贴板"""
        text = self.original_text.toPlainText()
        if text:
            clipboard = QApplication.clipboard()
            clipboard.setText(text)
            QMessageBox.information(self, "提示", "原文已复制到剪贴板")

    def copy_translated(self):
        """复制翻译内容到剪贴板"""
        text = self.translated_text.toPlainText()
        if text:
            clipboard = QApplication.clipboard()
            clipboard.setText(text)
            QMessageBox.information(self, "提示", "翻译已复制到剪贴板")

    def update_translation_display(self, text):
        """更新翻译显示窗口"""
        if not self.translation_display:
            return
        
        # 保存当前翻译窗口的位置（如果窗口可见）
        saved_position = None
        if self.translation_display.isVisible():
            saved_position = self.translation_display.geometry()
        
        # 更新翻译窗口的位置和大小
        if self.selected_region:
            # 如果翻译窗口还没有显示过，则设置初始位置（在选中区域下方）
            if not saved_position:
                # 将屏幕像素坐标转换为Qt逻辑坐标
                qt_rect = self.selected_region
                self.translation_display.move(
                    qt_rect.x(),
                    qt_rect.bottom() + 10
                )
            else:
                # 如果窗口已经显示过，保持用户设置的位置
                self.translation_display.setGeometry(saved_position)
                
            # 设置大小与选择区域完全一致
            self.translation_display.update_size(
                self.selected_region.width(),  # 使用检测区域的精确宽度
                self.selected_region.height()
            )
            
            # 获取翻译窗口的几何信息
            translation_rect = self.translation_display.geometry()
            # 获取选择区域的几何信息（转换为Qt逻辑坐标进行比较）
            selection_qt_rect = self.selected_region
            
            # 检查是否重叠
            if translation_rect.intersects(selection_qt_rect):
                self.translation_display.setText("与识别区域重叠，请移出识别区域！")
                # 如果正在自动翻译，暂停翻译
                if self.is_running and self.translation_worker:
                    self.translation_worker.pause_translation()
            else:
                # 如果没有重叠，显示翻译内容
                self.translation_display.setText(text)
                # 如果正在自动翻译，恢复翻译
                if self.is_running and self.translation_worker:
                    self.translation_worker.resume_translation()
        else:
            # 如果没有选择区域，保持当前位置并显示翻译内容
            if saved_position:
                self.translation_display.setGeometry(saved_position)
            self.translation_display.setText(text)
            if self.is_running and self.translation_worker:
                self.translation_worker.resume_translation()
        
        # 显示翻译窗口
        self.translation_display.show()
        
        # 连接移动信号
        if not hasattr(self, '_translation_display_moved_connected'):
            self.translation_display.moved.connect(self.on_translation_display_moved)
            self._translation_display_moved_connected = True

    def on_translation_display_moved(self):
        """处理翻译窗口移动事件"""
        # 标记用户已经移动过翻译窗口
        self._translation_window_moved = True
        # 如果正在自动翻译，暂停翻译
        if self.translation_worker:
            self.translation_worker.pause_translation()
        # 使用QTimer延迟检查重叠，避免频繁检查
        QTimer.singleShot(500, self.check_overlap_and_resume)

    def check_overlap_and_resume(self):
        """检查重叠并恢复翻译"""
        if not self.selected_region or not self.translation_display:
            return
        
        # 获取翻译窗口的几何信息
        translation_rect = self.translation_display.geometry()
        # 获取选择区域的几何信息（转换为Qt逻辑坐标进行比较）
        selection_qt_rect = self.selected_region
        
        # 检查是否重叠
        if translation_rect.intersects(selection_qt_rect):
            # 显示重叠提示
            self.translation_display.setText("与识别区域重叠，请移出识别区域！")
            # 如果正在自动翻译，保持暂停状态
            if self.is_running:
                return
        else:
            # 如果没有重叠，恢复之前的翻译内容
            if self.translated_text.toPlainText():
                self.translation_display.setText(self.translated_text.toPlainText())
                # 如果之前是自动翻译模式，恢复自动翻译
                if self.is_running and self.translation_worker:
                    self.translation_worker.resume_translation()

    def resume_translation(self):
        """恢复翻译"""
        if self.translation_worker:
            self.translation_worker.resume_translation()

    def close_region(self):
        """关闭绘制区域"""
        # 如果正在自动翻译，先停止翻译
        if self.is_running:
            self.stop_translation()
            
        if self.region_display:
            self.region_display.hide()
        if self.translation_display:
            self.translation_display.hide()
        self.selected_region = None
        self.start_btn.setEnabled(False)
        self.stop_btn.setEnabled(False)

    def closeEvent(self, event):
        """关闭事件处理"""
        # 保存背景设置
        self.save_background_settings()

        # 保存当前翻译API、OCR选项和识别语言
        from config.settings import load_config, save_config
        config = load_config()
        # 翻译API
        api_text = self.api_combo.currentText() if hasattr(self, 'api_combo') else None
        ocr_text = self.ocr_service_combo.currentText() if hasattr(self, 'ocr_service_combo') else None
        lang_text = self.language_combo.currentText() if hasattr(self, 'language_combo') else None
        # 下拉框文本与config映射
        api_reverse = {"deepseek-chat": 'deepseek', "百度翻译": 'baidu', "腾讯翻译": 'tencent', "阿里翻译": 'aliyun'}
        ocr_mapping = {"本地OCR": "local", "腾讯OCR": "tencent", "百度OCR": "baidu"}
        if api_text:
            config['selected_api'] = api_reverse.get(api_text, 'deepseek')
        if ocr_text:
            config['selected_ocr'] = ocr_mapping.get(ocr_text, 'local')
        if lang_text:
            config['selected_language'] = lang_text
        save_config(config)

        # 关闭时同时关闭所有显示窗口
        if self.region_display:
            self.region_display.close()
        if self.adjust_buttons:
            self.adjust_buttons.close()
        if self.translation_display:
            self.translation_display.close()
        # 停止翻译线程
        if self.translation_worker:
            self.translation_worker.stop()
        event.accept()

    def update_window_style(self):
        """更新窗口样式"""
        style = """
            QMainWindow {
                background-color: #fafafa;
            }
            QPushButton {
                background-color: rgba(0, 120, 212, 0.7);
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 6px;
                font-family: "Microsoft YaHei UI";
                font-size: 13px;
                min-width: 90px;
                font-weight: 500;
            }
            QPushButton:hover {
                background-color: rgba(16, 110, 190, 0.7);
            }
            QPushButton:pressed {
                background-color: rgba(0, 90, 158, 0.7);
            }
            QPushButton:disabled {
                background-color: rgba(224, 224, 224, 0.7);
                color: #666666;
            }
            QTextEdit {
                background-color: rgba(255, 255, 255, 0.7);
                border: 1px solid rgba(224, 224, 224, 0.7);
                border-radius: 6px;
                padding: 12px;
                font-family: "Microsoft YaHei UI";
                font-size: 13px;
                selection-background-color: rgba(0, 120, 212, 0.7);
                selection-color: white;
            }
            QLabel {
                font-family: "Microsoft YaHei UI";
                font-size: 13px;
                color: #202020;
                font-weight: 500;
                background-color: rgba(255, 255, 255, 0.7);
                padding: 4px 8px;
                border-radius: 4px;
            }
            QComboBox {
                background-color: rgba(255, 255, 255, 0.7);
                color: #202020;
                border: 1px solid rgba(224, 224, 224, 0.7);
                padding: 8px 16px;
                border-radius: 6px;
                font-family: "Microsoft YaHei UI";
                font-size: 13px;
                min-width: 120px;
                font-weight: 500;
            }
            QComboBox:hover {
                border-color: rgba(0, 120, 212, 0.7);
            }
            QComboBox:pressed {
                border-color: rgba(0, 90, 158, 0.7);
            }
            QComboBox::drop-down {
                border: none;
                width: 24px;
            }
            QComboBox::down-arrow {
                image: url(down_arrow.png);
                width: 14px;
                height: 14px;
            }
            QComboBox QAbstractItemView {
                background-color: rgba(255, 255, 255, 0.7);
                color: #202020;
                border: 1px solid rgba(224, 224, 224, 0.7);
                border-radius: 6px;
                selection-background-color: rgba(0, 120, 212, 0.7);
                selection-color: white;
                padding: 8px;
                font-family: "Microsoft YaHei UI";
                font-size: 13px;
            }
            QGroupBox {
                font-family: "Microsoft YaHei UI";
                font-size: 13px;
                border: 1px solid rgba(224, 224, 224, 0.7);
                border-radius: 6px;
                margin-top: 16px;
                padding-top: 20px;
                font-weight: 500;
                background-color: rgba(255, 255, 255, 0.7);
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 8px;
                color: #202020;
                background-color: rgba(255, 255, 255, 0.7);
            }
        """
        # 不再设置QSS的background-image，由paintEvent负责绘制背景
        self.setStyleSheet(style)

    def show_background_dialog(self):
        """显示背景设置对话框"""
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.FileMode.ExistingFile)
        file_dialog.setNameFilter("图片文件 (*.png *.jpg *.jpeg *.bmp)")
        
        if file_dialog.exec():
            selected_files = file_dialog.selectedFiles()
            if selected_files:
                image_path = selected_files[0]
                
                # 验证图片是否可以加载
                pixmap = QPixmap(image_path)
                if pixmap.isNull():
                    QMessageBox.critical(self, "错误", "无法加载所选图片，请确保图片格式正确且未损坏。")
                    return
                
                # 创建背景图片目录
                if getattr(sys, 'frozen', False):
                    # 打包后的应用，使用exe文件所在目录
                    bg_dir = os.path.join(os.path.dirname(sys.executable), 'assets', 'backgrounds')
                else:
                    # 开发环境
                    bg_dir = os.path.join(self.base_path, 'assets', 'backgrounds')
                
                os.makedirs(bg_dir, exist_ok=True)
                
                # 生成安全的文件名
                timestamp = time.strftime("%Y%m%d%H%M%S")
                file_ext = os.path.splitext(image_path)[1].lower()
                safe_filename = f"bg_{timestamp}{file_ext}"
                bg_path = os.path.join(bg_dir, safe_filename)
                
                try:
                    # 复制图片到背景目录
                    shutil.copy2(image_path, bg_path)
                    
                    # 验证复制的图片
                    bg_pixmap = QPixmap(bg_path)
                    if bg_pixmap.isNull():
                        raise Exception("复制的图片无法加载")
                    
                    # 更新背景图片（使用绝对路径）
                    self.background_image = os.path.abspath(bg_path)
                    self.save_background_settings()
                    self.update_window_style()
                    
                    QMessageBox.information(self, "成功", "背景图片设置成功！")
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"设置背景图片失败：{str(e)}")
                    # 清理失败的图片
                    if os.path.exists(bg_path):
                        try:
                            os.remove(bg_path)
                        except:
                            pass

    def load_background_settings(self):
        """加载背景图片设置"""
        try:
            # 获取应用程序的基础路径
            if getattr(sys, 'frozen', False):
                # 如果是打包后的应用，使用exe文件所在目录
                base_path = os.path.dirname(sys.executable)
                print(f"打包后的应用路径: {base_path}")
            else:
                # 如果是开发环境
                base_path = os.path.dirname(os.path.dirname(__file__))
                print(f"开发环境路径: {base_path}")

            # 首先尝试从配置文件加载用户设置的背景图片
            settings_path = os.path.join(base_path, 'config', 'background.json')
            print(f"尝试加载配置文件: {settings_path}")
            print(f"配置文件是否存在: {os.path.exists(settings_path)}")

            if os.path.exists(settings_path):
                with open(settings_path, 'r', encoding='utf-8') as f:
                    settings = json.load(f)
                    bg_path = settings.get('background_image')
                    if bg_path:
                        # 转换为绝对路径
                        abs_path = os.path.abspath(bg_path)
                        print(f"从配置文件加载背景图片: {abs_path}")
                        print(f"配置文件中的背景图片是否存在: {os.path.exists(abs_path)}")
                        
                        if os.path.exists(abs_path):
                            # 验证图片是否可以加载
                            pixmap = QPixmap(abs_path)
                            if not pixmap.isNull():
                                print(f"成功加载配置文件中的背景图片: {abs_path}")
                                self.background_image = abs_path
                                return  # 成功加载用户设置的背景图片，直接返回
                            else:
                                print(f"无法加载配置文件中的背景图片: {abs_path}")
                        else:
                            print(f"配置文件中的背景图片不存在: {abs_path}")

            # 如果没有找到用户设置的背景图片，则使用默认背景图片
            if getattr(sys, 'frozen', False):
                # 打包后的应用，从临时目录加载默认背景
                default_bg = os.path.join(sys._MEIPASS, 'assets', 'backgrounds', 'bg_20250623134155.jpg')
            else:
                # 开发环境
                default_bg = os.path.join(base_path, 'assets', 'backgrounds', 'bg_20250623134155.jpg')
            
            print(f"尝试加载默认背景图片: {default_bg}")
            print(f"默认背景图片是否存在: {os.path.exists(default_bg)}")

            if os.path.exists(default_bg):
                # 验证图片是否可以加载
                pixmap = QPixmap(default_bg)
                if not pixmap.isNull():
                    print(f"成功加载默认背景图片: {default_bg}")
                    self.background_image = default_bg
                    # 只有在没有用户设置的情况下才保存默认背景图片到配置文件
                    if not os.path.exists(settings_path):
                        config_dir = os.path.join(base_path, 'config')
                        os.makedirs(config_dir, exist_ok=True)  # 创建配置目录
                        settings = {
                            'background_image': default_bg
                        }
                        with open(settings_path, 'w', encoding='utf-8') as f:
                            json.dump(settings, f, indent=4, ensure_ascii=False)
                    return
                else:
                    print(f"无法加载默认背景图片: {default_bg}")

            # 如果都没有找到，设置为None
            self.background_image = None
        except Exception as e:
            print(f"加载背景设置失败: {str(e)}")
            self.background_image = None

    def save_background_settings(self):
        """保存背景图片设置"""
        try:
            # 获取正确的配置目录路径
            if getattr(sys, 'frozen', False):
                # 如果是打包后的应用，使用exe文件所在目录
                config_dir = os.path.join(os.path.dirname(sys.executable), 'config')
            else:
                # 如果是开发环境
                config_dir = os.path.join(self.base_path, 'config')
            
            os.makedirs(config_dir, exist_ok=True)
            
            settings_path = os.path.join(config_dir, 'background.json')
            print(f"保存背景设置到: {settings_path}")
            
            if self.background_image and os.path.exists(self.background_image):
                # 验证图片是否可以加载
                pixmap = QPixmap(self.background_image)
                if not pixmap.isNull():
                    # 保存绝对路径
                    abs_path = os.path.abspath(self.background_image)
                    abs_path = abs_path.replace('\\', '/')  # 统一使用正斜杠
                    settings = {
                        'background_image': abs_path
                    }
                    print(f"保存背景图片路径: {abs_path}")
                else:
                    settings = {
                        'background_image': None
                    }
                    print("背景图片无法加载，保存为None")
            else:
                settings = {
                    'background_image': None
                }
                print("没有背景图片或文件不存在，保存为None")
            
            with open(settings_path, 'w', encoding='utf-8') as f:
                json.dump(settings, f, indent=4, ensure_ascii=False)
            print(f"背景设置保存成功: {settings_path}")
        except Exception as e:
            print(f"保存背景设置失败: {str(e)}")

    def nativeEvent(self, eventType, message):
        """处理原生窗口事件，修正多屏DPI下WM_NCHITTEST幽灵区"""
        if eventType == b"windows_generic_MSG":
            msg = ctypes.wintypes.MSG.from_address(int(message))
            if msg.message == 0x0084:  # WM_NCHITTEST
                x = msg.lParam & 0xFFFF
                y = (msg.lParam >> 16) & 0xFFFF
                # 获取当前窗口所在屏幕
                screen = self.window().windowHandle().screen()
                dpi_ratio = screen.devicePixelRatio() if screen else 1.0
                logical_x = int(x / dpi_ratio)
                logical_y = int(y / dpi_ratio)
                pos = self.mapFromGlobal(QPoint(logical_x, logical_y))
                edge_size = 5
                if pos.x() <= edge_size:
                    if pos.y() <= edge_size:
                        return True, 0x0D  # HTTOPLEFT
                    elif pos.y() >= self.height() - edge_size:
                        return True, 0x10  # HTBOTTOMLEFT
                    else:
                        return True, 0x0A  # HTLEFT
                elif pos.x() >= self.width() - edge_size:
                    if pos.y() <= edge_size:
                        return True, 0x0E  # HTTOPRIGHT
                    elif pos.y() >= self.height() - edge_size:
                        return True, 0x11  # HTBOTTOMRIGHT
                    else:
                        return True, 0x0B  # HTRIGHT
                elif pos.y() <= edge_size:
                    return True, 0x0C  # HTTOP
                elif pos.y() >= self.height() - edge_size:
                    return True, 0x0F  # HTBOTTOM
        return False, 0 

    def update_toggle_button(self):
        """更新切换按钮的图标"""
        if self.donation_visible:
            icon_path = os.path.join(self.base_path, 'assets', 'arrow_left.svg')
        else:
            icon_path = os.path.join(self.base_path, 'assets', 'arrow_right.svg')
            
        print(f"箭头图标路径: {icon_path}")
        print(f"箭头图标文件是否存在: {os.path.exists(icon_path)}")
        if os.path.exists(icon_path):
            self.toggle_donation_btn.setIcon(QIcon(icon_path))
            self.toggle_donation_btn.setIconSize(QSize(24, 24))
            
    def toggle_donation_window(self):
        """切换打赏窗口的显示状态"""
        if self.donation_visible:
            # 隐藏打赏窗口
            start_rect = self.donation_window.geometry()
            end_rect = QRect(
                self.geometry().right() - 200,
                start_rect.top(),
                200,
                start_rect.height()
            )
            # 设置透明度动画
            self.opacity_animation.setStartValue(1.0)
            self.opacity_animation.setEndValue(0.0)
        else:
            # 显示打赏窗口
            start_rect = self.donation_window.geometry()
            end_rect = QRect(
                self.geometry().right() + 5,
                start_rect.top(),
                200,
                start_rect.height()
            )
            # 设置透明度动画
            self.opacity_animation.setStartValue(0.0)
            self.opacity_animation.setEndValue(1.0)
            
        self.donation_animation.setStartValue(start_rect)
        self.donation_animation.setEndValue(end_rect)
        
        # 同时启动两个动画
        self.donation_animation.start()
        self.opacity_animation.start()
        
        self.donation_visible = not self.donation_visible
        self.update_toggle_button()
        
    def moveEvent(self, event):
        """窗口移动时更新打赏窗口位置"""
        super().moveEvent(event)
        if self.donation_window.isVisible():
            self.donation_window.move(self.geometry().right() + 5, self.geometry().top())
            
    def resizeEvent(self, event):
        """窗口大小改变时更新打赏窗口位置"""
        super().resizeEvent(event)
        if self.donation_window.isVisible():
            self.donation_window.move(self.geometry().right() + 5, self.geometry().top())

    def on_ocr_service_changed(self, ocr_name):
        if ocr_name == "本地OCR":
            self.language_combo.clear()
            self.language_combo.addItems(self.local_languages)
            self.language_combo.setCurrentText("英语")
        elif ocr_name == "腾讯OCR":
            self.language_combo.clear()
            self.language_combo.addItems(self.tencent_languages)
            self.language_combo.setCurrentText("中文")
        elif ocr_name == "百度OCR":
            self.language_combo.clear()
            self.language_combo.addItems(self.baidu_languages)
            self.language_combo.setCurrentText("中文")

    def listen_shortcut(self):
        import keyboard
        keyboard.add_hotkey('ctrl+q', self.handle_quick_select)
        keyboard.wait()

    def handle_quick_select(self):
        # 用QTimer保证在主线程执行
        QTimer.singleShot(0, self.quick_select_area)

    def quick_select_area(self):
        # 获取主窗口中心点
        main_center = self.geometry().center()
        # 获取所有屏幕
        screens = QApplication.screens()
        # 判断主窗口在哪个屏幕
        main_screen = None
        for screen in screens:
            if screen.geometry().contains(main_center):
                main_screen = screen
                break
        # 获取当前鼠标所在屏幕
        cursor_pos = QCursor.pos()
        cursor_screen = None
        for screen in screens:
            if screen.geometry().contains(cursor_pos):
                cursor_screen = screen
                break
        # 只有在主窗口和鼠标在同一屏幕时才最小化
        if main_screen is not None and cursor_screen is not None and main_screen == cursor_screen:
            self.showMinimized()
        self.select_area()

    def restore_main_window(self):
        self.showNormal()
        self.raise_()
        self.activateWindow() 

    def on_api_combo_changed(self, api_name):
        config = load_config()
        if api_name == "deepseek-chat":
            ok = bool(config.get('deepseek', {}).get('api_key'))
        elif api_name == "百度翻译":
            ok = bool(config.get('baidu', {}).get('app_id')) and bool(config.get('baidu', {}).get('app_key'))
        elif api_name == "腾讯翻译":
            ok = bool(config.get('tencent', {}).get('secret_id')) and bool(config.get('tencent', {}).get('secret_key'))
        elif api_name == "阿里翻译":
            ok = bool(config.get('aliyun', {}).get('access_key')) and bool(config.get('aliyun', {}).get('access_secret'))
        else:
            ok = False
        if not ok:
            QMessageBox.warning(self, "配置不完整", "配置不完整，请先在API配置中填写相关信息。")
            # 恢复为上一个可用API
            # 读取当前config['selected_api']，并设置api_combo
            api_mapping = {'deepseek': "deepseek-chat", 'baidu': "百度翻译", 'tencent': "腾讯翻译", 'aliyun': "阿里翻译"}
            selected_api = config.get('selected_api', 'deepseek')
            self.api_combo.blockSignals(True)
            self.api_combo.setCurrentText(api_mapping.get(selected_api, "deepseek-chat"))
            self.api_combo.blockSignals(False)
        else:
            # 切换成功，保存选择
            api_reverse = {"deepseek-chat": 'deepseek', "百度翻译": 'baidu', "腾讯翻译": 'tencent', "阿里翻译": 'aliyun'}
            config['selected_api'] = api_reverse.get(api_name, 'deepseek')
            save_config(config)

    def paintEvent(self, event):
        super().paintEvent(event)
        if self.background_image and os.path.exists(self.background_image):
            painter = QPainter(self)
            pixmap = QPixmap(self.background_image)
            if not pixmap.isNull():
                win_w, win_h = self.width(), self.height()
                img_w, img_h = pixmap.width(), pixmap.height()
                scale = min(win_w / img_w, win_h / img_h)
                new_w, new_h = int(img_w * scale), int(img_h * scale)
                x = (win_w - new_w) // 2
                y = (win_h - new_h) // 2
                painter.drawPixmap(x, y, new_w, new_h, pixmap)